package com.wangjiacai.utils.csv;

import com.wangjiacai.utils.utils.BeanUtil;
import com.wangjiacai.utils.utils.Gb2312Util;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class CSVUtil {

    public static <T> void exportCSV(List<T> list, Class<T> type, OutputStream outputStream) throws IOException {
        Field[] fields = type.getDeclaredFields();
        List<CSVPOJO> candidateFields = new ArrayList<>();
        for (Field field : fields) {
            CSVElement csvElement = field.getAnnotation(CSVElement.class);
            if (csvElement != null) {
                CSVPOJO csvpojo = new CSVPOJO();
                csvpojo.setCsvElement(csvElement);
                csvpojo.setName(field.getName());
                candidateFields.add(csvpojo);
            }
        }
        candidateFields.sort((e1, e2) -> e1.getCsvElement().order() - e2.getCsvElement().order());
        for(int i=0;i<candidateFields.size();i++){
            CSVPOJO csvpojo=candidateFields.get(i);
            if(i==candidateFields.size()-1) outputStream.write(Gb2312Util.getBytes(csvpojo.getName()+"\n"));
            else outputStream.write(Gb2312Util.getBytesWithComma(csvpojo.getName()));
        }
        for (T t : list) {
            for(int i=0;i<candidateFields.size();i++){
                Object value=BeanUtil.getPropertyValue(t,candidateFields.get(i).getName(),Object.class);
                if(i==candidateFields.size()-1) outputStream.write(Gb2312Util.getBytes(value+"\n"));
                else outputStream.write(Gb2312Util.getBytesWithComma(value));
            }
        }
    }
}
